<?php
/**
 * @package html
 */
require_once '_dbobject.php';
require_once '_localemanager.php';
require_once '_img.php';
require_once '_system.php';
require_once '_stringex.php';
require_once '_htmlbase.php';

/**
 * Class which encapsulates view of offers in the list view.
 */
class HtmlOfferList extends HtmlOfferBase {
	/**
	 * @see HtmlBase::fetchInstance
	 * @return HtmlOfferList
	 */
	static function fetchInstance(resource $resource) {
		try {
			return new HtmlOfferList($resource);
		} catch(ExceptionResourceEmpty $e) {
			return false;
		}
	}
	
	/**
	 * Generate html code, but don't outpu it yet.
	 * @see HtmlObject::processMe
	 */
	function processMe() {
		$cm = CodeManager::getCodeManager();
		$info = SiteContext::getSiteContext();
		$dbObject = $this->dbObject;
		
		$href = self::hrefToOffer($dbObject->id);
		
		$ifInterestedThenCheckedInput = $info->isInterestedInItem($dbObject->id) && @$_GET[Constants::REQ_ACTION] != Constants::REQ_ACTION_INTERESTEDIN ? 'checked="checked" ' : "";
		
		$rentOrSale = $this->dbObject->rentOrSale == 'sale' ? $cm->get("30084") : $cm->get("30085");
		
		$this->buffer = "
			<tr class=\"_TEMPLATE_ODDOREVEN_\">
				<td class=\"first\">
					<input type=\"checkbox\" value=\"offer-$dbObject->id\" $ifInterestedThenCheckedInput/>
				</td>
				<td>
					" . Definitions::getSetupLocalitiesSafe($dbObject->locality) . "
				</td>
				<td>
					$dbObject->town
				</td>
				<td>
					$dbObject->street			
				</td>
				<td class=\"align-right\">
					" . LocaleManager::valueFormatted($dbObject->size) . " m&sup2;
				</td>
				<td class=\"align-right\">
					" . LocaleManager::price($dbObject->price, $dbObject->currency) . "		
				</td>
				<td>
					$rentOrSale
				</td>
				<td class=\"last\">
					<a href=\"$href\" title=\"Podrobnosti k nabídce id $dbObject->id\">".$cm->get("30009")."</a>
				</td>
			</tr>";
	}
	
	
	/**
	 * Map which connects a parameter from an url with
	 * an attribute of HtmlBase::$dbObject
	 */
	private static $sortValMap = array (
		Constants::REQ_SORTVAL_LOCALITY => "locality",
		Constants::REQ_SORTVAL_STREET => "street",
		Constants::REQ_SORTVAL_SIZE => "size",
		Constants::REQ_SORTVAL_PRICE => "price",
		Constants::REQ_SORTVAL_TOWN => "town",
		Constants::REQ_SORTVAL_RENTORSALE => "rentOrSale"
	);
	
	/**
	 * Provides extra scalability then just HtmlObject::init
	 *
	 * @see HtmlObject::init
	 * 
	 * @param string $query
	 * @param bool $displayErrors
	 * @param bool $availableSort
	 * @param bool $availableItemsCountSetting
	 * @param bool $availableFooter
	 */
	public static function initWithFullQuery($query, $displayErrors = false, $availableSort = true, $availableItemsCountSetting = true, $availableFooter = true) {
		$logger = Logger::getLogger();
		$info = SiteContext::getSiteContext();
		
		// Get connector
		$res = $info->getDBConnector()->query($query);
		
		
		echo "
			<table id=\"offer-list\">
				<thead>
					<tr>
						<td class=\"first\">
							<input type=\"checkbox\" id=\"offer-list-selectall\" />
						</td>";
		$cm = CodeManager::getCodeManager();
		$columnsSpecs = array(
			array(Constants::REQ_SORTVAL_LOCALITY, $cm->get("30013")),
			array(Constants::REQ_SORTVAL_TOWN, $cm->get("30014")),
			array(Constants::REQ_SORTVAL_STREET, $cm->get("30015")),
			array(Constants::REQ_SORTVAL_SIZE, $cm->get("30016")),
			array(Constants::REQ_SORTVAL_PRICE, $cm->get("30017")),
			array(Constants::REQ_SORTVAL_RENTORSALE, $cm->get("30086"))
		);
		foreach($columnsSpecs as $params) {
			if ($availableSort) {
				echo self::headerColumn($params[0], $params[1]);
			} else {
				echo "<td>$params[1]</td>";
			}
		}
		echo "		
						<td class=\"last\">
						</td>
					</tr>
				</thead>";
		if ($availableFooter) {
			echo '
					<tfoot>
						<tr>';
			if (Policy::isAdminView()) {
				echo '
							<td class="first" colspan="4">';
				echo '
								<a class="light" href="javascript: Ajax.getIdsForSelectedOffersAndDelete(this); ">'.$cm->get("30058").' <img src="/img/o_drop.png" alt="remove" /></a>
								&nbsp;|&nbsp;
								<a class="light" href="javascript: Ajax.getIdsForSelectedOffersAndHide(this); ">Hide selected</a>
							';
								
			} else {
				echo '
							<td class="first" colspan="4">';
				if (@$_GET[Constants::REQ_ACTION] == Constants::REQ_ACTION_INTERESTEDIN) {
					echo '
								<a class="light" href="javascript: Ajax.getIdsForSelectedOffersAndRemoveInListView(this); ">'.$cm->get("30058").'</a>
								'.$cm->get("30059").'.';
				} else {
					echo '
								<a class="light" href="javascript: Ajax.getIdsForSelectedOffersAndAddInListView(this); ">'.$cm->get("30055").'</a>
								'.$cm->get("30056").'
								<a class="light" href="?'.Constants::REQ_ACTION.'='.Constants::REQ_ACTION_INTERESTEDIN.'" >
									'.$cm->get("30057").'
								</a>.';
				}
			}
			echo '
							</td>
							<td class="last" colspan="4">';
			if ($availableItemsCountSetting) {
				echo '
								'.$cm->get("10020").': 
								<select onchange="Ajax.setCountOfPagesForListView(this.value);" class="small" name="offer-list-defaultpagescount">';
				foreach (Constants::$SETUP_COUNTOFITEMSINLISTVIEW as $availableCountOfItems) {
					if ($availableCountOfItems == $info->getCountOfItemsInListView()) {
						echo "
									<option value=\"$availableCountOfItems\" selected=\"selected\">$availableCountOfItems</option>";
					} else {
						echo "
									<option value=\"$availableCountOfItems\">$availableCountOfItems</option>";
					}
				}
			echo '				
								</select>';
			}
			echo '
							</td>
						</tr >
					</tfoot>';
		}
		echo "
				<tbody>";
		$isEmpty = true;
		for($i = 0; $htmlOfferList = HtmlOfferList::fetchInstance($res); ++$i) {
			Logger::getLogger()->debug("processing offer: " . $htmlOfferList->dbObject->id);
			try {
				$htmlOfferList->processMe();
				$htmlOfferList->replaceTemplate("/_TEMPLATE_ODDOREVEN_/", $i % 2 == 0 ? "even" : "odd");
				$htmlOfferList->flushMe();
				$isEmpty = false;
			} catch (Exception $e) {
				$logger->error("Cannot display offer: '".$htmlOfferList->dbObject->id."' due to error: '$e'");
				if ($displayErrors) {
					Error::getError()->addErrorMessage($cm->get("30205", array($htmlOfferList->dbObject->id)));
				}
			}
		}
		if ($isEmpty) {
			echo "<tr><td>".$cm->get("30202")."</td></tr>";
			Error::getError()->addNoticeMessage($cm->get("30202"));
		}
		echo '
				</tbody>
				
			</table>';
	}
	/**
	 * Method which should group together number of calls of HtmlObject::processMe and HtmlObject::flushMe
	 * in a cycle.
	 * @see HtmlObject::init
	 *
	 * @param bool $querySpec
	 * @param boll $displayErrors
	 */
	public static function init($querySpec = null, $displayErrors = false) {
		$logger = Logger::getLogger();
		$info = SiteContext::getSiteContext();
		$cm = CodeManager::getCodeManager();
		
		if ($querySpec == null) {
			$querySpec = " where status = 'visible' ";
		} else {
			$querySpec .= " AND status = 'visible' ";
		}
		
		// Fetch datas for pages counting
		self::fetchDataForPagesCounting($info->getCountOfItemsInListView(), $querySpec);
		
		// Sort output
		$query = "";
		if (@isset($_REQUEST[Constants::REQ_SORTVAL]) && @isset($_REQUEST[Constants::REQ_SORTTYPE])
			&& @self::$sortValMap[$_REQUEST[Constants::REQ_SORTVAL]] && @self::$sortTypeMap[$_REQUEST[Constants::REQ_SORTTYPE]]) {
			$query = " ORDER BY `offers`.`".self::$sortValMap[$_REQUEST[Constants::REQ_SORTVAL]]."` ".self::$sortTypeMap[$_REQUEST[Constants::REQ_SORTTYPE]];
		}
			
		// Decide if click on column header will sort ascending or descending
		if (@$_REQUEST[Constants::REQ_SORTTYPE] == Constants::REQ_SORTTYPE_ASC)
			$sortType = Constants::REQ_SORTTYPE_DESC;
		else
			$sortType = Constants::REQ_SORTTYPE_ASC;
		
		$hrefDefault = $info->getSiteInf()->urlRelativeWithoutSomeVariables(array(
				Constants::REQ_SORTTYPE => true, 
				Constants::REQ_SORTVAL => true, 
				Constants::REQ_TYPEOFVIEW => true
		));
		
		self::$href = Common::addParamsToUrl($hrefDefault, Constants::REQ_SORTTYPE, $sortType,
				Constants::REQ_SORTVAL, "_TEMPLATESORT_",
				Constants::REQ_TYPEOFVIEW, Constants::REQ_TYPEOFVIEW_LIST
		);
		
		self::$hrefAsc = Common::addParamsToUrl($hrefDefault, Constants::REQ_SORTTYPE, Constants::REQ_SORTTYPE_ASC, 
				Constants::REQ_SORTVAL, "_TEMPLATESORT_", 
				Constants::REQ_TYPEOFVIEW, Constants::REQ_TYPEOFVIEW_LIST);
		self::$hrefDesc = Common::addParamsToUrl($hrefDefault, Constants::REQ_SORTTYPE, Constants::REQ_SORTTYPE_DESC, 
				Constants::REQ_SORTVAL, "_TEMPLATESORT_", 
				Constants::REQ_TYPEOFVIEW, Constants::REQ_TYPEOFVIEW_LIST);
		
		if (!Policy::isAdminView()) {
			echo '
			<div class="text left">
				<a href="'.
					Common::addParamToUrl(
							$info->getSiteInf()->urlRelativeWithoutSomeVariables(array(Constants::REQ_TYPEOFVIEW => true)),
							Constants::REQ_TYPEOFVIEW, Constants::REQ_TYPEOFVIEW_THUMB)
					."\">".$cm->get("30054")."</a>
			</div>";
		}
		echo "
			<div class=\"offer-list-pages\">";

		// display page numbers
		for ($page = 1; $page <= self::$countOfPages; ++$page) {
			if ($page == self::$currentPage) {
				echo '
				<span>&nbsp;'.
				$page.'&nbsp;</span>';
			} else {
				echo "
				<a href=\"".Common::addParamsToUrl(self::$hrefPages, Constants::REQ_PAGE, $page)."\">$page</a>";
			}
		}
		echo "
			</div>";
		if (!Policy::isAdminView()) {
			echo "<div class=\"cleaner\"></div>";
		}
		self::initWithFullQuery(Constants::DB_QUERY_OFFERS_ALL.$querySpec.$query.self::$queryLimit, $displayErrors, true, true);
	}
}
?>